/******************************************************************************
* Copyright (C) 2018, Huada Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Huada Semiconductor Co.,Ltd ("HDSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with HDSC
* components. This software is licensed by HDSC to be adapted only
* for use in systems utilizing HDSC components. HDSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. HDSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2016-05-08  1.0  Lux First version for Device Driver Library of Module.
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/
#include "gpio.h"

#include "ddl.h"
#include "uart.h"
#include "bt.h"
#include "lpm.h"
#include "gpio.h"
#include "flash.h"
#include "app_spi_io.h"
#include "lvd.h"
#include "gpio.h"
#include "reset.h"
#include "wdt.h"
#include "vc.h"
#include "gpio.h"
#include "bgr.h"


#include "locker_ctr.h"

#include "app_uart.h"
#include "sys_parameter.h"

/* xiaobo  git test */
/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/
#define  COMM_TIMEOUT  (10ul)  //2000   //100ms
/******************************************************************************
 * Global variable definitions (declared in header file with 'extern')
 ******************************************************************************/
 
volatile uint32_t  flag_10ms = 0;
volatile uint32_t  DelayTick = 0;

volatile uint8_t  Locker_state_1to8;
volatile uint8_t  Locker_state_9to16;
volatile uint8_t  Locker_state_17to18; 

//typedef struct __SYS_PARAMETER  *_SYS_PARAMETER ;//
typedef struct __SYS_PARA   *_SYS_PARAMETER ;	    //
_SYS_PARAMETER _pSYS;       //ADT

typedef  int(*pFun)(void)  ;	


/******************************************************************************
 * Local type definitions ('typedef')
 ******************************************************************************/

/******************************************************************************
 * Local function prototypes ('static')
 ******************************************************************************/
extern void App_UartInit(void);
extern void App_SPIInit(void);


/******************************************************************************
 * Local variable definitions ('static')                                      *
 ******************************************************************************/

static uint32_t  Tim2_initial_val;

/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/

/*****************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
 
 /*******************************************************************************
 * BT1中断服务函数   选择工作模式 1为 32位 32位自由计数模式，
                     到最大 0XFFFFFFFF 溢出后产生中断，
                     定时 /计数器变为 0X00000000;然后继续计数；
 
 ****************************************************/
 /*  不同于 HC32F003
void Tim2_IRQHandler(void)
{             //Bt_GetIntFlag
    if (TRUE == Bt_GetIntFlag(TIM2,BtUevIrq))
    {
        Bt_ClearIntFlag(TIM2,BtUevIrq);
        Bt_Cnt32Set(TIM2, ( ~( Tim2_initial_val ) + 1 ) );  //1s  注意  Pclk 必需同  Hclk
        flag_10ms = 1;
			  if( DelayTick )	 --DelayTick;
			  Uart1_Dec_time_out_value(   );
		}
}
*/
/*******************************************************************************
 * BT1中断服务函数
 ******************************************************************************/
void Tim0Int(void)
{
    static uint8_t i;
    
    if(TRUE == Bt_GetIntFlag(TIM0, BtUevIrq))
    {
        //Bt_Cnt32Set(TIM2, ( ~( Tim2_initial_val ) + 1 ) );  //1s  注意  Pclk 必需同  Hclk
			  Bt_M0_Cnt32Set( TIM0 , ( ~( Tim2_initial_val ) + 1 ) );
        flag_10ms = 1;
			  if( DelayTick )	 --DelayTick;
			  Uart1_Dec_time_out_value(   );
        
        Bt_ClearIntFlag(TIM0,BtUevIrq);
    }
}



void  Delay_tick( int tick )
{
	   __disable_irq();
 	   DelayTick = tick;  
	   __enable_irq();
	   while (DelayTick) ;	   
}

void  Set_TimeOut_tick( int tick )
{
	   __disable_irq();
 	   DelayTick = tick;  
	   __enable_irq();	   
}
int   Check_TimeOut_tick( void )
{
	  return DelayTick;
}

void Delay(uint32_t ucnt)
{
    volatile uint32_t i = ucnt;

    while (i--);	 //20ns  at 50MHz
}

// TIMER0  MODE 0  32BIT
void init_timer00()
{ 
	  uint16_t                  u16ArrValue;
    uint16_t                  u16CntValue;
    stc_bt_mode0_config_t     stcBtBaseCfg;
    stc_gpio_config_t         stcLEDPortCfg;
	  
	  DDL_ZERO_STRUCT(stcBtBaseCfg);
    DDL_ZERO_STRUCT(stcLEDPortCfg);
	  //打开BT外设时钟
	  Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); //GPIO 外设时钟使能
    Sysctrl_SetPeripheralGate(SysctrlPeripheralBTim, TRUE); //Base Timer外设时钟使能
	  
	  stcBtBaseCfg.enWorkMode = BtWorkMode0;                  //定时器模式
    stcBtBaseCfg.enCT       = BtTimer;                      //定时器功能，计数时钟为内部PCLK
    stcBtBaseCfg.enPRS      = BtPCLKDiv1;                  //PCLK/64  to 1
    stcBtBaseCfg.enCntMode  = Bt32bitFreeMode;//Bt16bitArrMode;  //32位计数器/定时器or自动重载16位计数器/定时器
    stcBtBaseCfg.bEnTog     = FALSE;
    stcBtBaseCfg.bEnGate    = FALSE;
    stcBtBaseCfg.enGateP    = BtGatePositive;
    
    stcBtBaseCfg.pfnTim0Cb  = Tim0Int; //中断函数入口
    
    Bt_Mode0_Init(TIM0, &stcBtBaseCfg);  
    //设置计数值，启动计数
		Tim2_initial_val = SystemCoreClock/100;   // 10ms		
		Bt_M0_Cnt32Set( TIM0 , ( ~( Tim2_initial_val ) + 1 ) );
		 Bt_ClearIntFlag(TIM0,BtUevIrq);                         //清中断标志   
    Bt_Mode0_EnableIrq(TIM0);                               //使能TIM0中断(模式0时只有一个中断)
    EnableNvic(TIM0_IRQn, IrqLevel3, TRUE);                 //TIM0中断使能
    
    Bt_M0_Run(TIM0);                                        //TIM0 运行。
		  
}
//////////////////////////////////////////////////////////////
//systick中断函数
void SysTick_IRQHandler(void)
{
    flag_10ms = 1;
}

extern void  spi_out_595( uint8_t TxData );
//void Vc1_IRQHandler(void)
void 	VcIrqCallback(void)
{
	  //if( Vc_GetStat(VcChannel0,VcIntrResult) == TRUE )
    CLOSE_ALL_LOCKER(); 
		Vc_ClearIrq(VcChannel1);
}
/**
 ******************************************************************************
 ** \brief  初始化VC1
 **
 ** \return 无
 ******************************************************************************/
static int App_VC1Init(void)
{   
	  stc_vc_channel_config_t stcChannelConfig;
    stc_vc_dac_config_t  VcDacStruct;
	
    DDL_ZERO_STRUCT(stcChannelConfig);//变量清0
    DDL_ZERO_STRUCT( VcDacStruct );//变量清0
	
    if (Ok != Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE))//开GPIO时钟
    {
        return 1;
    }
    if (Ok != Sysctrl_SetPeripheralGate(SysctrlPeripheralVcLvd, TRUE))//开LVD时钟
    {
        return 1;
    } 
    if (Ok != Sysctrl_SetPeripheralGate(SysctrlPeripheralAdcBgr, TRUE))//开adc时钟
    {
        return 1;
    }    
    //Bgr_BgrEnable();                                         //BGR必须使能		
		M0P_BGR->CR_f.BGR_EN = 0x1u;                 //BGR必须使能
    M0P_BGR->CR_f.TS_EN = 0x0u;
    delay100us(1);
		Gpio_SetAnalogMode(GpioPortB,GpioPin12);//模拟输入  VcChannel1
		
		VcDacStruct.bDivEn = 1;
	  VcDacStruct.enDivVref = VcDivVrefAvcc;
	  VcDacStruct.u8DivVal = 5;//10;  //8 
	  Vc_DACInit( &VcDacStruct );
		
		stcChannelConfig.enVcChannel = VcChannel1;//VcChannel0;
    stcChannelConfig.enVcCmpDly  = VcDelayoff;//VcDelay10mv; //VC0迟滞电压约为10mV  VcDelayoff;    //迟滞关闭
    stcChannelConfig.enVcFilterTime = VcFilter14us;//VcFilter28us;//VC输出滤波时间约为28us
    stcChannelConfig.enVcInPin_P = VcInPCh9;  //VC1_CH9的P端连接PB12
    //stcChannelConfig.enVcInPin_N = VcInNCh0;//AiBg1p2;
		stcChannelConfig.enVcInPin_N = ResDivOut;//AiBg1p2;//VC0_CH的N端连接内核1.2V   ResDivOut
    stcChannelConfig.enVcIrqSel = VcIrqRise;//VcIrqFall;  ///< 上升沿触发
		stcChannelConfig.enVcBiasCurrent = VcBias20ua;// 20uA(需要开启BGR，BGR启动时间大约20us)
    stcChannelConfig.enVcOutConfig = VcOutDisable;
    stcChannelConfig.pfnAnalogCmpCb = VcIrqCallback;
    Vc_EnableFilter(VcChannel1);
    Vc_ChannelInit(VcChannel1,&stcChannelConfig);
		Vc_ClearIrq(VcChannel1);
    Vc_EnableIrq(VcChannel1);
    Vc_EnableChannel(VcChannel1);
		EnableNvic(VC1_IRQn, IrqLevel0, TRUE);  //IrqLevel3
	
}

////////////////////////////////////////////////////////////
//时钟初始化配置
void App_ClkInit(void)
{
	  stc_sysctrl_clk_config_t stcCfg;
	   
	///< 开启FLASH外设时钟
    Sysctrl_SetPeripheralGate(SysctrlPeripheralFlash, TRUE);
	   ///<========================== 时钟初始化配置 ===================================
    ///< 因要使用的时钟源HCLK小于24M：此处设置FLASH 读等待周期为0 cycle(默认值也为0 cycle)
    Flash_WaitCycle(FlashWaitCycle0);
    
    ///< 时钟初始化前，优先设置要使用的时钟源：此处设置RCH为4MHz
    Sysctrl_SetRCHTrim(SysctrlRchFreq4MHz);
    
    ///< 选择内部RCH作为HCLK时钟源;
    stcCfg.enClkSrc    = SysctrlClkRCH;
    ///< HCLK SYSCLK/1
    stcCfg.enHClkDiv   = SysctrlHclkDiv1;
    ///< PCLK 为HCLK/1
    stcCfg.enPClkDiv   = SysctrlPclkDiv1;
    ///< 系统时钟初始化
    Sysctrl_ClkInit(&stcCfg);  
}
//将时钟从RCH4MHz切换至RCH24MHz, 切换时钟后，“外设要重新初始化”
void App_Rch4MHzTo24MHz(void)
{
///<============== 将时钟从RCH4MHz切换至RCH24MHz ==============================    
    ///< RCH内部时钟的切换需要从低到高依次切换到目标时钟（默认4MHz -> 24MHz）
    ///< RCH时钟的频率切换，需要先将时钟切换到RCL
    Sysctrl_SetRCLTrim(SysctrlRclFreq32768);
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, TRUE);
    Sysctrl_SysClkSwitch(SysctrlClkRCL);
    
    ///< 加载目标频率的RCH的TRIM值
    Sysctrl_SetRCHTrim( SysctrlRchFreq22_12MHz );  //SysctrlRchFreq24MHz
    ///< 使能RCH（默认打开，此处可不需要再次打开）
    //Sysctrl_ClkSourceEnable(SysctrlClkRCH, TRUE);
    ///< 时钟切换到RCH
    Sysctrl_SysClkSwitch(SysctrlClkRCH);
    ///< 关闭RCL时钟
    Sysctrl_ClkSourceEnable(SysctrlClkRCL, FALSE);

    ///< 使能HCLK从PA01输出
    //Gpio_SfHClkOutputCfg(GpioSfHclkOutEnable, GpioSfHclkOutDiv1);

    //delay1ms(3000);
    //_UserKeyWait(); //USER KEY 按下后继续执行

    ///< 禁止HCLK从PA01输出
    //Gpio_SfHClkOutputCfg(GpioSfHclkOutDisable, GpioSfHclkOutDiv1);

}

void LvdIrqCallback(void)
{  
    Lvd_DisableIrq();
    //Gpio_WriteOutputIO(GpioPortD,GpioPin5,bPortVal);//中断受触发设置限制，LVD输出不受限制
}
static int App_LvdInit(void)
{
	  stc_lvd_config_t stcLvdCfg;

    DDL_ZERO_STRUCT(stcLvdCfg);//变量清0
	  if (Ok != Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE))//开GPIO时钟
    {
        return 1;
    }
    if (Ok != Sysctrl_SetPeripheralGate(SysctrlPeripheralVcLvd, TRUE))//开LVD时钟
    {
        return 1;
    }
	  stcLvdCfg.bLvdReset = TRUE; //FALSE;//配置中断或者RESET功能
    stcLvdCfg.enInput = LvdInputVCC;//配置LVD输入口  ///< 配置LVD输入源
    stcLvdCfg.enThreshold = LvdTH2p6V;//配置LVD基准电压
    stcLvdCfg.bFilter = TRUE;  ///< 滤波使能
    stcLvdCfg.enFilterTime = LvdFilter29ms; ///< 滤波时间设置
    stcLvdCfg.enIrqType = LvdIrqHigh;   ///< 复位触发类型
    //stcLvdCfg.pfnIrqCbk = LvdIrqCallback;

    Lvd_Init(&stcLvdCfg);
    //Lvd_EnableIrq(stcLvdCfg.enIrqType);
    delay100us(1);
		/////< LVD 模块使能
    Lvd_Enable();//LVD使能 
}

static void App_WdtInit(void)
{
	   stc_wdt_config_t  stcWdt_Config;
	   DDL_ZERO_STRUCT(stcWdt_Config);
	   Sysctrl_SetPeripheralGate(SysctrlPeripheralWdt,TRUE);//
	   stcWdt_Config.u8LoadValue = 0x0b;//3.2s  1011：3.28s
     stcWdt_Config.enResetEnable = WRESET_EN;//WINT_EN;//WINT_EN;//WRESET_EN;////
     //stcWdt_Config.pfnWdtIrqCb = WdtCallback;    
     Wdt_Init(&stcWdt_Config);   
     Wdt_Start();
	   Wdt_Feed();
	
}

void  led_io_initial( void )
{
	  stc_gpio_config_t pstcGpioCfg;
    
    ///< 打开GPIO外设时钟门控
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);
    
    ///< 端口方向配置->输出
    pstcGpioCfg.enDir = GpioDirOut;
    ///< 端口驱动能力配置->高驱动能力
    pstcGpioCfg.enDrv = GpioDrvH;
    ///< 端口上下拉配置->无上下拉
    pstcGpioCfg.enPuPd = GpioNoPuPd;
    ///< 端口开漏输出配置->开漏输出关闭
    pstcGpioCfg.enOD = GpioOdEnable;//GpioOdDisable;
    ///< 端口输入/输出值寄存器总线控制模式配置->AHB
    pstcGpioCfg.enCtrlMode = GpioAHB;
    
    ///< GPIO IO PD05初始化（PD05在STK上外接LED）
    Gpio_Init(GpioPortD, GpioPin7, &pstcGpioCfg);  //led1
	  Gpio_Init(GpioPortD, GpioPin6, &pstcGpioCfg);  //led2
	  Gpio_SetIO(GpioPortD, GpioPin6); 
	  //Gpio_ClrIO(GpioPortD, GpioPin6);
	  Gpio_SetIO(GpioPortD, GpioPin7);  
	  Gpio_ClrIO(GpioPortD, GpioPin7);  //led1
		Gpio_WriteOutputIO(GpioPortD,GpioPin7,0);
}

void check_locker_state( void )
{
	  uint32_t  read_address_sw;
	  read_address_sw =  check_ir_address( );
								   if( (read_address_sw&0x00ff0000) == 0x00A50000 )
									 {
										   Locker_state_1to8  = read_address_sw &0xff;
										   Locker_state_9to16 = (read_address_sw>>8) &0xff;
										   Locker_state_17to18 =  Gpio_GetInputIO( IN_17_PORT, IN_17_PIN )  |  \
										                         (Gpio_GetInputIO( IN_18_PORT, IN_18_PIN ) <<1 ) ;
									 }
}
/**
 ******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 ** This sample
 **
 ******************************************************************************/
static  int  command_proc( );
extern int get_switch_address( void );
int32_t main(void)
{
	  static uint32_t  count_10ms = 0; 
	  uint32_t  read_address_sw;
	  stc_reset_cause_t reset_cause;
	  //******************************************************************************************
	  ///< 打开GPIO外设时钟门控 如果没有打开GPIO外设时钟，所有IO操作都是未知的，*************************
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);//首先打开GPIO外设时钟 其他外设同
	  CLOSE_ALL_LOCKER();
	  
	  Reset_GetCause( &reset_cause );
	  
	  App_LvdInit();
	
    App_ClkInit( );
	  App_Rch4MHzTo24MHz( );
	  delay1ms(10);
	  //SystemCoreClockUpdate();
    led_io_initial( );
	   
	  do   //地址在低4BIT
	  {
			  read_address_sw  = get_switch_address();
	      sys_data.address =  read_address_sw  ;
		    __nop();__nop();__nop();__nop();__nop();__nop();
			  __nop();__nop();__nop();__nop();__nop();__nop();
			  delay1ms(10);
		    read_address_sw  = get_switch_address();			 
			  if( ((read_address_sw & 0x0f ) == sys_data.address)  )
				{
					   break;
				}
		       
	   }while(1);
		 //read_sys_parameter_sector( );
		 
		 ////电流检测，过流保护 	
		App_VC1Init( );
	  App_WdtInit( ); // watchdog
	
	  init_timer00();
	     ///< UART 初始化
    App_UartInit();
	  App_SPIInit( );
	  while(1)
    while(1)
    {
         if( flag_10ms )  //
				 {
              flag_10ms = 0;
					    if( ++count_10ms > 10)
							{
								   count_10ms  = 0;
								   //Gpio_ReadOutputIO(LED_PORT, LED_PIN);
								   //Gpio_WriteOutputIO(LED_PORT, LED_PIN, !Gpio_ReadOutputIO(LED_PORT, LED_PIN) );     //输出高，熄灭LED;
							     *( (volatile uint32_t *)( (uint32_t)&M0P_GPIO->PAOUT + GpioPortD) ) ^= ((1UL)<<(GpioPin7));
							 		 check_locker_state(   );						
								   
							}
							Wdt_Feed(); // 喂狗
							
				 }
         if ( Rx_buff_empty()  )
	       {
		         command_proc();														
	       }
         CLOSE_ALL_LOCKER(); 				 
    }
}

unsigned char buff[32];
unsigned int  address_min;
unsigned int  address_max;
/// 接收指令和返回的一定不要相同
static int  command_proc( )
{
       int i;
       int ret;
       int locker_num;

	      unsigned char temp;

	     address_min = (sys_data.address)*16;   //*12;   *16
	     address_max = (sys_data.address+1)*16;  //*12;  *16
       for( i = 0 ; i < 8 ;  )
       {
             if( getchar_timeout( &temp,COMM_TIMEOUT) )  return 0x01;
             if( 0==i )
             {
                  if( 0xc0 != temp )  continue;
             }
             buff[i++] =  temp;             
       }
	     if( ( buff[0] == 0xc0 ) && ( buff[7] == 0Xc0) ) 
	     {
	         temp = buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
             // must processed the address information   (buff[1]  is address  or locker_num)
	         //if ( (buff[6] == temp)    &&  (buff[1] > address_min ) && (buff[1] <= address_max ) )
           if ( (buff[6] == temp) ) 						 
			     {
				         //if( (buff[2] ==  0x01) && (buff[1] == sys_data.address) )      //OPEN 
				        if( (buff[2] ==  0x01) && (buff[1] > address_min ) && (buff[1] <= address_max ) ) 
						    {
                                  // locker_num = (buff[1]- address_min);
                                   open_locker( buff[1]- address_min );                                
                                   //check_locker_num( locker_num ); // 20151007    测试状态不对 ？？？
                                   //Update_Locker_state();                             
							                    //open_lock_CMD();							                    
							                     buff[2] =   0xf1;
                                   buff[3] =   Locker_state_1to8;
							                     buff[4] =   Locker_state_9to16;
                                   buff[5] =   Locker_state_17to18;
					                         buff[6] =   buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
						                      //return 0;   
				         }
								 else if( (buff[2] ==  0x11) && (buff[1] > address_min ) && (buff[1] <= address_max ) ) 
						     {
                                  // locker_num = (buff[1]- address_min);
                                   open_locker_double( buff[1]- address_min );                                
                                   //check_locker_num( locker_num ); // 20151007    测试状态不对 ？？？
                                   //Update_Locker_state();                             
							                    //open_lock_CMD();  
							                     buff[2] =   0xf1;
                                   buff[3] =   Locker_state_1to8;
							                     buff[4] =   Locker_state_9to16;
									                 buff[5] =   Locker_state_17to18;
					                         buff[6] =   buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
						                       //return 0;   
				         }				         
				         else if( (buff[2] == 0x03) && ( buff[1] == sys_data.address ) )   //set address
				         {
                             
                                   sys_data.address = buff[3];
                                   buff[2] =   0xf3;									 
							                     write_sys_parameter_sector( );				        
						                       //send_data_rep( buff );
				         }
				         else if( (buff[2] == 0x05) && (buff[1] == sys_data.address ) )   //check comm
				         {                        
                                  buff[3]  =  0x00;
									                buff[2] =   0xf5;
                                  buff[6]  =  buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
				         }
				         else if( (buff[2] == 0x06) && (buff[1] == 0xff) )   //check query address
				         {//c0 ff 06 00 00 00 f9 c0
                                   buff[1] =  sys_data.address;
									                 buff[2] =   0xf6;
					                         buff[6] =   buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
						                      //send_data_rep( buff );
				         }

						     else if( (buff[2] == 0x10) && ( (buff[1] > address_min ) && (buff[1] <= address_max ) ) )  //check ir
				         {
                                   buff[2] =   0xfa;
                                   buff[3] =   Locker_state_1to8;
							                     buff[4] =   Locker_state_9to16;
                                   buff[5] =   Locker_state_17to18;
					                         buff[6] =   buff[1] ^buff[2]^buff[3]^buff[4]^buff[5];
				         } 						
                 else
                         return 1;  //否则 会出现一直有返回数据

								 Gpio_WriteOutputIO(CTR485_PORT , CTR485_PIN , TRUE); //rs485 send
						     //os_dly_wait ( 2 );//os_dly_wait ( 3 );//os_dly_wait ( 10 );  10ms< t < 30ms
				         Delay_tick( 2 );//10ms _delay_ms(5);
				         send_command( buff,8 );
                 Delay_tick( 2 );//20ms _delay_ms(20); 
                 Gpio_WriteOutputIO(CTR485_PORT, CTR485_PIN , FALSE); 	//receive 							 
		             return 0;			 
		     }		     
	    }
	    return 1;
}


/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/


